from fastapi import HTTPException
from scorpio.core.common import AgentConfig

from scorpio.schemas import ChatRequest
from scorpio.agenthub import DefaultAgent
from scorpio.core.common import (
    WebSocketSender,
    OutputAdaptor,
    ScorpioConfig,
    AgentConfig,
    get_logger
)

from .provider import get_chosen_model_config, get_mcp_config 

logger = get_logger(__name__)

class DefaultAgentChat:
    def __init__(self, sender: WebSocketSender) -> None:
        self.agent="default"
        self.sender=sender
        self.adaptor=OutputAdaptor(sender)
        
    def _initialize(self,request: ChatRequest,  app_config: ScorpioConfig)-> HTTPException:
        model_param=get_chosen_model_config(app_config.models, request.provider, request.selected_model)
        if model_param is None:
            raise HTTPException(status_code=400, detail="无效的模型选择")
        mcp_config=get_mcp_config(app_config.mcp_servers, request.mcp_server)
        if mcp_config is None:
            raise HTTPException(status_code=400, detail="无效的MCP Server选择")
        self.agent_config=AgentConfig(mcp_config=mcp_config, model_parameter=model_param)
        return None
    
    async def chat(self, request: ChatRequest, app_config: ScorpioConfig)->str|HTTPException:
        #agent_config=AgentConfig(mcp_config=mcp_config, model_parameter=chosen_model)
        result=self._initialize(request, app_config)
        shared = {
            "question": request.question, 
            "system_prompt": "simple.md",
            "context": {
                "agent":{
                    "config": self.agent_config,
                    "mcp_server": request.mcp_server,
                },
                "sender": self.sender,
                "adaptor": self.adaptor,
                "messages": [],
                "events": [],
            }
        }
        agent=DefaultAgent(shared=shared)
        agent.create()
        step=await agent.run()
        logger.info(f"agent: {agent.name} end with step: {step}")
        return result